package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * 登录拦截器
 * @author benxin
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取登录用户 token
        String token = request.getHeader("authorization");
        System.out.println("=== RefreshTokenInterceptor token === " + token);
        if (StrUtil.isBlank(token)) {
            System.out.println("Token 为空，放行");
            return true;
        }

        // 从 redis 获取用户
        String key = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        System.out.println("=== Redis userMap === " + userMap);

        if (userMap.isEmpty()) {
            System.out.println("Redis 未找到用户，放行");
            return true;
        }

        // 将查出来的数据转化为对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        System.out.println("=== 转换后的 UserDTO === " + userDTO);

        // 保存用户到 ThreadLocal
        UserHolder.saveUser(userDTO);
        System.out.println("=== 已保存到 UserHolder === " + UserHolder.getUser());

        // 刷新过期时间
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.SECONDS);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
